package cn.xing.modules.app.listener;

import cn.xing.config.AlipayTemplate;
import cn.xing.modules.app.dto.PayAsyncDto;
import cn.xing.modules.app.service.OrderService;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@RestController
public class OrderPayListener {

    @Autowired
    private AlipayTemplate alipayTemplate;
    @Autowired
    private OrderService orderService;

    /**
     * 支付宝异步通知
     *
     * @param request
     * @return
     */
    @RequestMapping("/payed/notify")
    public String handleAlipay(PayAsyncDto payAsyncDto, HttpServletRequest request) throws Exception {
        try {
            // 1. 验签
            //获取支付宝POST过来反馈信息
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

            boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名

            // 延签结果
            if (signVerified) {
                log.info("签名验证成功");
                String result = orderService.handlePayResult(payAsyncDto);
                log.info("支付宝异步通知数据：{}", payAsyncDto);

                return result;

            } else {
                log.info("签名验证失败");

                return "fail";
            }
        }catch (Exception e){

            return "fail";
        }


    }
}
